package com.kuang.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

//练习Thread，实现一个多线程同步下载图片
public class TestThread02 extends Thread {
    private String url; //网络我图片地址
    private String FileName;   //保存的文件名

    public TestThread02(String url, String FileName) {
        this.url = url;
        this.FileName = FileName;
    }

    //下载图片线程的执行体
    @Override
    public void run() {
        super.run();
        WebDownloader webDownloader = new WebDownloader();
        try {
            webDownloader.downloader(url, FileName);
            System.out.println("下载的文件名：" + FileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TestThread02 testThread01 = new TestThread02("https://www.baidu.com/img/baidu_jgylogo3.gif", "copy1.png");
        TestThread02 testThread02 = new TestThread02("https://www.baidu.com/img/baidu_resultlogo@2.png", "copy2.png");
        TestThread02 testThread03 = new TestThread02("https://www.baidu.com/img/bd_logo1.png", "copy3.png");

        //理想状态是先下载t1，最后t2，最后t3
        //实质上是几乎同时执行，不一定是这个顺序
        testThread01.start();
        testThread02.start();
        testThread03.start();
    }
}

//下载器
class WebDownloader {
    //下载方法
    public void downloader(String url, String filename) throws IOException {

        try {
            FileUtils.copyURLToFile(new URL(url), new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常");
        }
    }
}